#include "device_protocol_processor.h"
#include "base_log.h"
#include <chrono>
#include <iomanip>
#include <sstream>

namespace El {
namespace Protocol {

DeviceProtocolProcessor &DeviceProtocolProcessor::GetInstance()
{
    static DeviceProtocolProcessor instance;
    return instance;
}

bool DeviceProtocolProcessor::Initialize()
{
    LOG_INFO("初始化设备协议处理器");
    return true;
}

void DeviceProtocolProcessor::RegisterMethodHandlers(
    std::unordered_map<std::string, std::function<nlohmann::json(const std::string&, const nlohmann::json&)>> &method_handlers)
{
    // 注册设备状态查询方法
    method_handlers["cameras.getStatus"] = [this](const std::string &id, const nlohmann::json &params) {
        return HandleCamerasGetStatus(id, params);
    };
    
    // 注册视频流获取方法
    method_handlers["cameras.getStream"] = [this](const std::string &id, const nlohmann::json &params) {
        return HandleCamerasGetStream(id, params);
    };
    
    // 注册事件订阅相关方法
    method_handlers["events.subscribe"] = [this](const std::string &id, const nlohmann::json &params) {
        return HandleEventsSubscribe(id, params);
    };
    
    method_handlers["events.unsubscribe"] = [this](const std::string &id, const nlohmann::json &params) {
        return HandleEventsUnsubscribe(id, params);
    };
    
    method_handlers["events.getSubscriptions"] = [this](const std::string &id, const nlohmann::json &params) {
        return HandleEventsGetSubscriptions(id, params);
    };
}

// 获取设备状态
nlohmann::json DeviceProtocolProcessor::HandleCamerasGetStatus(const std::string &id, const nlohmann::json &params)
{
    LOG_DEBUG("处理cameras.getStatus请求, 参数: {}", params.dump());
    
    // 检查必要参数
    if (!params.contains("camera_id") || !params["camera_id"].is_string()) {
        return CreateErrorResponse(id, 400, "缺少camera_id参数或格式不正确");
    }

    std::string camera_id = params["camera_id"];
    
    // TODO: 实际获取摄像头状态的逻辑
    // 这里为示例，返回模拟数据
    nlohmann::json status = {
        {"online", true},
        {"uptime", 86400},
        {"cpu_usage", 45},
        {"memory_usage", 128000000},
        {"storage", {
            {"total", 32000000000},
            {"used", 16000000000}
        }},
        {"network", {
            {"upload_speed", 2048000},
            {"download_speed", 512000}
        }}
    };

    return CreateSuccessResponse(id, status);
}

// 获取视频流
nlohmann::json DeviceProtocolProcessor::HandleCamerasGetStream(const std::string &id, const nlohmann::json &params)
{
    LOG_DEBUG("处理cameras.getStream请求, 参数: {}", params.dump());
    
    // 检查必要参数
    if (!params.contains("camera_id") || !params["camera_id"].is_string()) {
        return CreateErrorResponse(id, 400, "缺少camera_id参数或格式不正确");
    }

    std::string camera_id = params["camera_id"];
    std::string protocol = "rtsp"; // 默认协议
    
    if (params.contains("protocol") && params["protocol"].is_string()) {
        protocol = params["protocol"];
    }
    
    // TODO: 根据请求的协议类型，生成对应的流地址
    std::string url;
    if (protocol == "webrtc") {
        url = "wss://stream.example.com/webrtc/" + camera_id;
    } else if (protocol == "rtsp") {
        url = "rtsp://stream.example.com/rtsp/" + camera_id;
    } else if (protocol == "hls") {
        url = "https://stream.example.com/hls/" + camera_id + "/index.m3u8";
    } else {
        return CreateErrorResponse(id, 400, "不支持的协议类型: " + protocol);
    }
    
    // 计算过期时间 (当前时间 + 1小时)
    auto now = std::chrono::system_clock::now();
    auto expires_time = now + std::chrono::hours(1);
    auto expires_time_t = std::chrono::system_clock::to_time_t(expires_time);
    
    std::stringstream ss;
    ss << std::put_time(std::gmtime(&expires_time_t), "%Y-%m-%dT%H:%M:%SZ");
    std::string expires_at = ss.str();
    
    nlohmann::json result = {
        {"url", url},
        {"expires_at", expires_at}
    };

    return CreateSuccessResponse(id, result);
}

// 订阅事件
nlohmann::json DeviceProtocolProcessor::HandleEventsSubscribe(const std::string &id, const nlohmann::json &params)
{
    LOG_DEBUG("处理events.subscribe请求, 参数: {}", params.dump());
    
    // 检查必要参数
    if (!params.contains("event_type") || !params["event_type"].is_string()) {
        return CreateErrorResponse(id, 400, "缺少event_type参数或格式不正确");
    }
    
    // 订阅信息
    Subscription sub;
    sub.id = "sub-" + std::to_string(std::chrono::system_clock::now().time_since_epoch().count());
    sub.event_type = params["event_type"];
    sub.active = true;
    
    // 获取回调URL (可选)
    if (params.contains("callback_url") && params["callback_url"].is_string()) {
        sub.callback_url = params["callback_url"];
    }
    
    // 获取过滤条件 (可选)
    if (params.contains("filters") && params["filters"].is_object()) {
        sub.filters = params["filters"];
    }
    
    // 设置创建时间
    auto now = std::chrono::system_clock::now();
    auto now_t = std::chrono::system_clock::to_time_t(now);
    std::stringstream ss;
    ss << std::put_time(std::gmtime(&now_t), "%Y-%m-%dT%H:%M:%SZ");
    sub.created_at = ss.str();
    
    // 保存订阅
    subscriptions_[sub.id] = sub;
    
    // 返回订阅信息
    nlohmann::json result = {
        {"subscription_id", sub.id},
        {"status", "active"}
    };
    
    return CreateSuccessResponse(id, result);
}

// 取消订阅
nlohmann::json DeviceProtocolProcessor::HandleEventsUnsubscribe(const std::string &id, const nlohmann::json &params)
{
    LOG_DEBUG("处理events.unsubscribe请求, 参数: {}", params.dump());
    
    // 检查必要参数
    if (!params.contains("subscription_id") || !params["subscription_id"].is_string()) {
        return CreateErrorResponse(id, 400, "缺少subscription_id参数或格式不正确");
    }
    
    std::string subscription_id = params["subscription_id"];
    
    // 查找订阅
    auto it = subscriptions_.find(subscription_id);
    if (it == subscriptions_.end()) {
        return CreateErrorResponse(id, 404, "找不到指定的订阅: " + subscription_id);
    }
    
    // 删除订阅
    subscriptions_.erase(it);
    
    // 返回成功
    nlohmann::json result = {
        {"subscription_id", subscription_id},
        {"status", "canceled"}
    };
    
    return CreateSuccessResponse(id, result);
}

// 获取订阅列表
nlohmann::json DeviceProtocolProcessor::HandleEventsGetSubscriptions(const std::string &id, 
                                                                    const nlohmann::json &params)
{
    LOG_DEBUG("处理events.getSubscriptions请求");
    
    // 可选的过滤参数
    std::string event_type;
    if (params.contains("event_type") && params["event_type"].is_string()) {
        event_type = params["event_type"];
    }
    
    // 收集订阅信息
    nlohmann::json subscriptions = nlohmann::json::array();
    
    for (const auto &pair : subscriptions_) {
        const Subscription &sub = pair.second;
        
        // 过滤事件类型
        if (!event_type.empty() && sub.event_type != event_type) {
            continue;
        }
        
        nlohmann::json sub_json = {
            {"id", sub.id},
            {"event_type", sub.event_type},
            {"created_at", sub.created_at},
            {"active", sub.active}
        };
        
        if (!sub.callback_url.empty()) {
            sub_json["callback_url"] = sub.callback_url;
        }
        
        if (!sub.filters.is_null()) {
            sub_json["filters"] = sub.filters;
        }
        
        subscriptions.push_back(sub_json);
    }
    
    // 返回订阅列表
    nlohmann::json result = {
        {"total", subscriptions.size()},
        {"subscriptions", subscriptions}
    };
    
    return CreateSuccessResponse(id, result);
}

// 创建错误响应
nlohmann::json DeviceProtocolProcessor::CreateErrorResponse(const std::string &id, int code, 
                                                         const std::string &message, 
                                                         const nlohmann::json &data)
{
    nlohmann::json error = {
        {"code", code},
        {"message", message}
    };
    
    if (data != nullptr) {
        error["data"] = data;
    }
    
    nlohmann::json response = {
        {"id", id},
        {"error", error}
    };
    
    return response;
}

// 创建成功响应
nlohmann::json DeviceProtocolProcessor::CreateSuccessResponse(const std::string &id, 
                                                           const nlohmann::json &result)
{
    return {
        {"id", id},
        {"result", result}
    };
}

} // namespace Protocol
} // namespace El
